<template>
	<xn-form-container
		:title="formData.id ? '编辑设备信息' : '增加设备信息'"
		:width="700"
		v-model:open="open"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-row :gutter="16">
				<a-col :span="12">
					<a-form-item label="所属机构：" name="orgId">
						<a-select
							v-model:value="formData.orgId"
							class="xn-wd"
							placeholder="请选择所属机构"
							allow-clear
							:options="orgOptions"
							@change="onOrgChange"
						></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="设备类型：" name="typeId">
						<a-select
							v-model:value="formData.typeId"
							placeholder="请选择设备类型"
							:options="typeOptions"
							:disabled="!formData.orgId"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="设备名称：" name="name">
						<a-input v-model:value="formData.name" placeholder="请输入设备名称" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="设备编号：" name="code">
						<a-input v-model:value="formData.code" placeholder="请输入设备编号" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="设备状态：" name="status">
						<a-select v-model:value="formData.status" placeholder="请选择设备状态" :options="statusOptions" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="设备描述：" name="description">
						<a-input v-model:value="formData.description" placeholder="请输入设备描述" allow-clear />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="deviceInfoForm">
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import deviceInfoApi from '@/api/biz/deviceInfoApi'
	import bizUserApi from '@/api/biz/bizUserApi'
	import deviceTypeApi from '@/api/biz/deviceTypeApi'
	// 抽屉状态
	const open = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	// 表单数据
	const formData = ref({})
	const submitLoading = ref(false)
	const typeOptions = ref([])
	const statusOptions = ref([])

	const orgTreeData = ref([])
	const treeDefaultExpandedKeys = ref([])

	const typeTreeData = ref([])
	const typeTreeDefaultExpandedKeys = ref([])

	// 机构选项
	const orgOptions = ref([])

	// 获取机构树数据
	const getOrgTree = () => {
		bizUserApi.userOrgTreeSelector().then((res) => {
			if (res !== null) {
				orgTreeData.value = res
				// 默认展开前两级
				orgTreeData.value.forEach((item) => {
					if (item.parentId === '0') {
						treeDefaultExpandedKeys.value.push(item.id)
						if (item.children) {
							item.children.forEach((child) => {
								treeDefaultExpandedKeys.value.push(child.id)
							})
						}
					}
				})
			}
		})
	}

	// 获取机构下的设备类型树
	const getTypeTree = () => {
		deviceTypeApi.getAll().then((res) => {
			if (res !== null) {
				typeTreeData.value = res
				typeTreeDefaultExpandedKeys.value = res.filter((item) => item.isOrg).map((item) => item.id)

				orgOptions.value = res
					.filter((item) => item.isOrg)
					.map((item) => ({
						label: item.name,
						value: item.id
					}))
			}
		})
	}

	const onOrgChange = (orgId, isEdit = false) => {
		if (!isEdit) {
			formData.value.typeId = undefined
		}

		if (orgId) {
			const orgNode = typeTreeData.value.find((item) => item.id === orgId && item.isOrg)
			if (orgNode && orgNode.children) {
				typeOptions.value = orgNode.children.map((child) => ({
					label: child.name,
					value: child.id
				}))
			} else {
				typeOptions.value = []
			}
		} else {
			typeOptions.value = []
		}
	}

	// 打开抽屉
	const onOpen = (record) => {
		open.value = true
		getOrgTree()
		getTypeTree()
		if (record) {
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
			if (formData.value.orgId) {
				setTimeout(() => {
					onOrgChange(formData.value.orgId, true) // 添加 isEdit = true
				}, 100)
			}
		}
		statusOptions.value = tool.dictList('DEVICE_STATUS')
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		typeOptions.value = []
		open.value = false
	}
	// 默认要校验的
	const formRules = {
		name: [required('请输入设备名称')],
		code: [required('请输入设备编号')],
		typeId: [required('请输入设备类型')],
		status: [required('请输入设备状态')],
		orgId: [required('请选择所属机构')]
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				deviceInfoApi
					.deviceInfoSubmitForm(formDataParam, formDataParam.id)
					.then(() => {
						onClose()
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
